package com.example.huanhang.changzhouapp.util;

import android.os.Handler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import static com.example.huanhang.changzhouapp.network.Constant.SQL_CONNECTION;
import static com.example.huanhang.changzhouapp.network.Constant.SQL_DEVICES;
import static com.example.huanhang.changzhouapp.network.Constant.SQL_PASSWORD;
import static com.example.huanhang.changzhouapp.network.Constant.SQL_USERNAME;


/**
 * Created by hang on 2017/6/8
 * 1. 在子线程中执行
 * 2.  在主线程执行
 */
public class ThreadUtil {

    /**
     * 在子线程执行的方法
     *
     * @param runnable
     */
    public static void runOnBackThread(Runnable runnable) {
        ThreadPoolManager.getInstance().createThreadPool().execute(runnable);
    }

    private static Handler handler = new Handler();

    /**
     * 主线程执行
     *
     * @param runnable
     */
    public static void runOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }

    /**
     * 数据库操作工具类
     * @param sql sql语句
     * @return 返回值,result
     * @throws Exception
     */
    public static ResultSet result(String sql) throws Exception {
        Class.forName(SQL_DEVICES).newInstance();     //加载MYSQL JDBC驱动程序
        Connection connection = (Connection) DriverManager.getConnection(
                SQL_CONNECTION, SQL_USERNAME,SQL_PASSWORD);
        Statement statement = (Statement) connection.createStatement();
        return statement.executeQuery(sql);
    }
    public static boolean executeInsert(final String insertSql) {
        try {
            Class.forName(SQL_DEVICES).newInstance();
            Connection connection = DriverManager.getConnection(
                    SQL_CONNECTION, SQL_USERNAME, SQL_PASSWORD);
            Statement statement = connection.createStatement();
            return statement.execute(insertSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    //值为1成功
    public static int executeUpdate(final String updateSql) {
        try {
            Class.forName(SQL_DEVICES).newInstance();
            Connection connection = DriverManager.getConnection(
                    SQL_CONNECTION, SQL_USERNAME, SQL_PASSWORD);
            Statement statement = connection.createStatement();
            return statement.executeUpdate(updateSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
